<template>
  <view class="view"    >
	  <scroll-view scroll-y refresher-enabled refresher-threshold="50" @refresherrefresh="onRefresh"
	  			style="height: 100%;">
    <view class="login-view">
      <view class="t-login">
        <!-- 添加空值检查 -->
        <uni-card v-if="studentProfile" :title="studentProfile.studentName" :isFull="true">
          <!-- 优化学生信息显示，使用 flex 布局 -->
          <view class="info-container">
            <view class="info-item">
              <text class="label">ID</text>
              <text class="value">{{ studentProfile.ID }}</text>
            </view>
            <view class="info-item">
              <text class="label">班级</text>
              <text class="value">{{ studentProfile.class }}</text>
            </view>
            <view class="info-item">
              <text class="label">年级</text>
              <text class="value">{{ studentProfile.grade }}</text>
            </view>
            <view class="info-item">
              <text class="label">电话</text>
              <text class="value">{{ studentProfile.phone }}</text>
            </view>
            <view class="info-item">
              <text class="label">性别</text>
              <text class="value">{{ studentProfile.sex }}</text>
            </view>
            <view class="info-item">
              <text class="label">年龄</text>
              <text class="value">{{ studentProfile.age }}</text>
            </view>
            <view class="info-item">
              <text class="label">学号</text>
              <text class="value">{{ studentProfile.studentID }}</text>
            </view>
            <view class="info-item">
              <text class="label">姓名</text>
              <text class="value">{{ studentProfile.studentName }}</text>
            </view>
          </view>

          <view class="avatar-container">
            <img :src="studentProfile.picture" width="80" height="80" alt="">
          </view>

          <!-- 优化成绩显示，使用 v-for 动态渲染 -->
          <view class="scores-container">
            <text class="section-title">成绩</text>
            <view v-if="studentScores" class="score-list">


              <view v-for="(score, subject) in  filterScores(studentScores)" :key="subject" class="score-item">
                <text class="subject">{{ formatSubjectName(subject) }}</text>
                <text class="score-value">{{ score }}</text>
              </view>
            </view>
          </view>

          <button type="primary" @click="editStudent(studentScores)">编辑成绩</button>
        </uni-card>
        <!-- 当 studentProfile 为 null 时显示加载提示 -->
        <view v-else>加载中...</view>
      </view>
    </view>
	</scroll-view>
  </view>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { onLoad  } from '@dcloudio/uni-app';
import { findStudentProfile,findStudentScores } from '@/api/base.js';


const studentProfile = ref(null);
const studentScores = ref(null); // 修正变量名
// 定义一个响应式变量来存储获取到的 id
const id = ref('');
// 格式化科目名称
const formatSubjectName = (subject) => {
  const subjectMap = {
    uid: '学生UID',
    english: '英语',
    physics: '物理',
    chemistry: '化学',
    politics: '政治',
    physical_education: '体育',
    information_technology: '信息技术',
    network: '网络',
    UpdatedAt: '更新时间',
    CreatedAt: '创建时间'
  }

  return subjectMap[subject] || subject;
};
// 过滤非成绩字段
const filterScores = (scores) => {
  const nonScoreFields = ['uid', 'UpdatedAt', 'CreatedAt'];
  return Object.fromEntries(
      Object.entries(scores).filter(([key]) => !nonScoreFields.includes(key))
  );
};

// 在组件加载时获取 id
onLoad((options) => {
  id.value = options.id;
  // 调用函数获取学生档案和成绩
  getStudentProfileAndScores(id.value);

});

// 定义查找学生档案的函数
const searchStudent =  async () => {
  try {
    // 假设这里需要传递学生 ID 作为查询参数
    const [info, score] = await Promise.all([
      findStudentProfile(id.value),
      findStudentScores(id.value)
    ]);

    // findStudentScores
    // const response = await findStudentProfile({ ID: 1 });
    if (info.code === 0 && score.code=== 0 ) { // 假设响应码 0 表示请求成功
      console.log('查找学生档案成功:', info.data);
      console.log('查找学生成绩成功:', score.data);
      studentProfile.value = info.data;
      studentScores.value = score.data; // 修正变量名
    } else {

      uni.showToast({
        title: '查找学生档案或成绩失败',
        icon: 'none'
      });

      console.error('查找学生档案失败:', info);
      console.error('查找学生成绩失败:', score);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
// const editStudent
const editStudent = (e) => {
  // 跳转到编辑页面，并传递学生 ID
  // e.ID = id.value;
  console.log("传递的ID  为", e.ID )
  uni.navigateTo({
    url: `/pages/home/edit?ID=${e.ID}`
  });
};

onLoad((options) => {

  if (options && options.ID) {
    if (Array.isArray(options.ID)) {
      // 如果是数组，取第一个元素
      id.value = options.ID[0];
      console.log("获取到的ID  为", options.ID )
    } else {
      id.value = options.ID;
      console.log("获取到的ID  为", options.ID )
    }
  }
  searchStudent();

});

// 定义下拉刷新函数
const onRefresh = async () => {
	console.log("---- 刷新中")
  try {
    // 调用查找学生信息的函数
    await searchStudent();
    // 刷新完成，关闭刷新状态
    uni.stopPullDownRefresh();
    uni.showToast({
      title: '刷新成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('刷新失败:', error);
    // 刷新失败，关闭刷新状态
    uni.stopPullDownRefresh();
    uni.showToast({
      title: '刷新失败',
      icon: 'none'
    });
  }
};
 

</script>
<style>

.view {
  padding: 20rpx;
}

.info-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  align-items: center;
  width: 48%;
  padding: 10rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}

.label {
  width: 30%;
  color: #666;
  font-size: 28rpx;
}

.value {
  width: 70%;
  color: #333;
  font-size: 28rpx;
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}

.scores-container {
  margin-bottom: 20rpx;
}

.section-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.score-list {
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 10rpx;
}

.score-item {
  display: flex;
  justify-content: space-between;
  padding: 10rpx;
  border-bottom: 1rpx solid #eee;
}

.score-item:last-child {
  border-bottom: none;
}

.subject {
  font-size: 28rpx;
  color: #666;
}

.score-value {
  font-size: 28rpx;
  color: #333;
}
/* 已有样式代码 */
</style>